﻿package net.wangit.framework.config;

import java.util.HashMap;
import java.util.Map;

import net.wangit.MapList;
import net.wangit.framework.cache.Cache;
import net.wangit.framework.util.CacheUtil;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.ServerAccessException;
import net.wangit.jdbc.util.DBHelper;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class Pages {

	private static Log log = LogFactory
			.getLog(net.wangit.framework.config.Pages.class);
	private static final String SQL = "select uid from UNIT where pp=1 order by lmt"; //已发布单元

	public Pages() {
	}

	public static boolean contains(String domain, String unitId) {
		Map pages = getPages(domain);
		return pages.containsKey(unitId);
	}

	private static Map getPages(String domain) {
		Map pages = (Map) getCache().get(domain);
		if (pages == null) {
			reload(domain);
			return (Map) getCache().get(domain);
		} else {
			return pages;
		}
	}

	public static synchronized void reload(String domain) {
		Cache cache = getCache();
		cache.clear(domain);
		cache.put(domain, createPages(domain));
	}

	private static Map createPages(String domain) {
		Map map = new HashMap();
		DB db = DBHelper.getDomainDB(domain);
		MapList list;
		try {
			list = db.query(Pages.SQL);
		} catch (Exception e) {
			log.error((new StringBuilder("could not query unit in server: "))
					.append(domain).toString(), e);
			throw new ServerAccessException((new StringBuilder(
					"could not query unit in server: ")).append(domain)
					.toString());
		}
		for (int i = 0; i < list.size(); i++) {
			map.put(list.getRow(i).get("uid"), null);
		}
		return map;
	}

	private static Cache getCache() {
		return CacheUtil.getPagesCache();
	}

}
